package com.njwb.day09.exception.util;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Util {
    public static String formatDate(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }
    public static String formatDate(Date date,String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }







    //读=》字符串

    /**
     *
     * @param path
     * @return
     * @throws FileNotFoundException :文件没找到
     * @throws IOException ：IO异常
     */


    public static String readFile(String path) throws IOException{
        BufferedReader bufferedReader = null ;
        StringBuffer stringBuffer = new StringBuffer();
        Reader reader = null;
        //实例化的时候，先实例化节点流，然后在实例化过滤流
        reader = new FileReader(new File(path));
        bufferedReader = new BufferedReader(reader);
        String line = "";
        while((line=bufferedReader.readLine())!=null) {
            stringBuffer.append(line+"\r\n");
        };
        //关闭的时候倒着关闭
        closeResource(bufferedReader,reader);

        return stringBuffer.toString();
    }



    public static void writeTargetDataIntoFile(String targetData,String targetPath){
        BufferedWriter bufferedWriter = null ;
        Writer writer = null;
        try {
            //实例化的时候，先实例化节点流，然后在实例化过滤流
            writer = new FileWriter(new File(targetPath));
            bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(targetData);
            bufferedWriter.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭的时候倒着关闭
            closeResource(bufferedWriter,writer);
        }
    }


    public static void closeResource(Closeable...closeables) {
        try{
            for(Closeable closeable :closeables) {
                closeable.close();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }

    }
}
